<?php

namespace app\home\controller;

use app\Base;
use app\Request;
use app\service\home\ChatService;
use think\App;
use think\facade\Cache;
use think\response\Json;
use think\response\View;

/**
 * 聊天测试
 *
 * User : Du
 * Date : 2022/4/7
 * Time : 10:34
 * Class Chat
 * package projects\controller\home
 */
class Chat extends Base
{
    public $roomId;
    public $userName;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->roomId = request()->post('roomId', 0);
        $this->userName = request()->post('name', '');
    }

    /**
     * 主页面
     *
     * User : Du
     * Date : 2022/4/7
     * Time : 10:37
     * @param Request $request
     * @return View
     */
    public function index(Request $request): View
    {
        $id = $request->get('id', 1);
        return view('home/chatRoom', ['res' => $id]);
    }


    /**
     * 绑定用户
     *
     * User : Du
     * Date : 2022/4/7
     * Time : 10:39
     * @return Json
     */
    public function bingUser(): Json
    {
        $clientId = request()->post('clientId', '');
        $chat = new ChatService($this->roomId, $this->userName);
        $res = $chat->bingUser($clientId);
        return $this->returnData();
    }


    /**
     * 获取房间全部用户
     *
     * User : Du
     * Date : 2022/4/7
     * Time : 10:38
     * @return Json
     */
    public function getOnlineList(): Json
    {
        $model = new ChatService($this->roomId, $this->userName);
        $res = $model->getAllGroupList();
        $this->res['data'] = $res;
        return $this->returnData();
    }

    /**
     * 记录聊天记录
     *
     * User : Du
     * Date : 2022/4/7
     * Time : 10:38
     * @return Json
     */
    public function addSpeak(): Json
    {
        if ($this->roomId != 0) {
            $content = request()->post('content', '');
            $chat = new ChatService($this->roomId, $this->userName);
            $res = $chat->addSpeak($content);
        } else {
            $this->returnData(1, '未知聊天室');
        }
        return $this->returnData();
    }

    /**
     * 离开聊天室
     *
     * User : Du
     * Date : 2022/4/7
     * Time : 10:38
     * @return Json
     */
    public function disconnect(): Json
    {
        $clientId = request()->post('client_id', '');
        if ($clientId) {
            $redis = Cache::store('redis')->handler();
            $data = jsonToArray($redis->get($clientId));
            $chat = new ChatService($data['room_id'], $data['name']);
            $res = $chat->disconnect($data, $clientId);
            $redis->del($clientId);
        }
        return $this->returnData();
    }
}